<template>
    <div class="e-form">
        <BillTop @cancel="handleClose"></BillTop>
    <div class="tabs warningTabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                >
                </el-tab-pane>
                <el-tab-pane
                    label="主体信息"
                    name="mainInfo"
                    :disabled="clickTabFlag"
                >
                </el-tab-pane>
                <el-tab-pane
                    label="合同清单"
                    name="contractList"
                    :disabled="clickTabFlag"
                >
                </el-tab-pane>
                <el-tab-pane
                    label="保证金"
                    name="earnestMoney"
                    :disabled="clickTabFlag"
                >
                </el-tab-pane>
                <el-tab-pane
                    label="合同条款"
                    name="contractTerms"
                    :disabled="clickTabFlag"
                >
                </el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="attach"
                    :disabled="clickTabFlag"
                >
                </el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"></el-tab-pane
                >
                <el-tab-pane
                    label="变更签订记录"
                    name="changeSignLog"
                    :disabled="clickTabFlag"></el-tab-pane
                >
                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form :model="formData" :label-width="formLabelWidth" :rules="rulesBase" ref="rulesBase" class="demo-ruleForm">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="合同编号：">
                                            <span>{{ formData.contractNumber }}</span>
                                            <el-button class="btn-blue" style="margin-left:5px" @click="jumpContractDefinitionShow">查看</el-button>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="合同名称：">
                                            <span>{{formData.contractName}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="外包方：">
                                            <span>{{ formData.collaborativeTeam }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="所属机构：">
                                            <span>{{ formData.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="变更编号：">
                                            <span>{{ formData.changeNumber }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="合同类型：">
                                            <span>{{ subTypeForm[formData.contractType-1] }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="原合同金额：">
                                            <span>{{formData.originalContractAmount}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="不含税金额(元)：">
                                            <span>{{formData.taxExcludedAmount}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="税率%："
                                            prop="taxRate"
                                        >
                                            <el-input
                                                v-model="
                                                    formData.taxRate
                                                "
                                                v-enter-integer2="{
                                                    set: this,
                                                    val: 'formData',
                                                    key: 'taxRate'
                                                }"
                                                autocomplete="off"
                                                @change="monitorTaxRate"
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="税额：" prop="taxAmount">
                                            <el-input v-model="formData.taxAmount" v-enter-float="{set:this,val:'formData',key:'taxAmount'}" autocomplete="off" @change="monitorTax"></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="变更后合同金额：">
                                            <span>{{formData.amountAfterChange}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="变更日期：" prop="changeTime">
                                            <el-date-picker type="date" placeholder="请选择变更日期" value-format="yyyy-MM-dd" v-model="formData.changeTime" style="width: 100%;"></el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="变更期数：">
                                            <span>{{formData.period}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{options.applyStateForm[formData.state]}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="押金：" prop="deposit">
                                        <el-input v-model="formData.deposit" v-enter-float="{set:this,val:'formData',key:'deposit'}" autocomplete="off"></el-input>
                                        </el-form-item>
                                    </el-col>
                                <el-col :span="12">
                                        <el-form-item label="传输财务共享：" v-if="formData.contractState >= 4">
                                            <span class="redFont" v-if="formData.financialSharing === 0 || formData.financialSharing === 1 || formData.financialSharing === 2 || formData.financialSharing === 4">{{ financialSharingList[formData.financialSharing] }}</span>
                                            <span class="greenFont" v-if="formData.financialSharing === 3 || formData.financialSharing === 5">{{ financialSharingList[formData.financialSharing] }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="是否需要缴纳履约保证金：" prop="bondAmount">
                                            <el-switch
                                                v-model="formData.bondState"
                                                active-color="#06ad36"
                                                inactive-color="#C0CCDA"
                                                :active-value="true"
                                                :inactive-value="false"
                                                active-text="是"
                                                inactive-text="否"
                                                :disabled="bondState"
                                            >
                                            </el-switch>
                                            <el-input
                                                v-model="
                                                    formData.bondAmount
                                                "
                                                v-enter-float="{
                                                    set: this,
                                                    val: 'formData',
                                                    key: 'bondAmount'
                                                }"
                                                autocomplete="off"
                                                v-if="formData.bondState"
                                                style="margin-left:40px"
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="备注：">
                                            <el-input type="textarea" v-model="formData.contractContext" autocomplete="off"></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="本位币：">
                                            <span>{{formData.baseCurName}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="人民币汇率：">
                                            <span>{{formData.rmbRate}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="经办人：">
                                            <span>{{userInfo.userName}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <!-- 主体信息 -->
                    <div id="mainInfoCon" class="con">
                        <div class="tabs-title" id="mainInfo">主体信息</div>
                        <div style="width:100%" class="form">
                            <el-form
                                :model="formData"
                                :rules="rulesMain"
                                ref="rulesMain"
                                label-width="150px"
                            >
                                <div class="mainTitle">甲方信息</div>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="名称：">
                                            <span>{{ mainInfo.firstParty.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="开户银行：">
                                            <span>{{ mainInfo.firstParty.bankName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="开户账号：">
                                            <span>{{ mainInfo.firstParty.accountNumber }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="联系电话：">
                                            <span>{{ mainInfo.firstParty.phone }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="法人代表：">
                                            <span>{{ mainInfo.firstParty.legalRepresentative }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="传 真：">
                                            <span>{{ mainInfo.firstParty.fax }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="委托代理：">
                                            <span>{{ mainInfo.firstParty.principalAgent }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="邮政编码：" >
                                            <span>{{ mainInfo.firstParty.postalCode }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="所在地址：">
                                            <span> {{ showAddress(mainInfo.firstParty.address) }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <div class="mainTitle">乙方信息</div>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="招标：">
                                            <span>{{ mainInfo.secondParty.biddingName }}</span>
                                            <el-button v-if="mainInfo.secondParty.biddingId" class="btn-blue" style="margin-left:5px" @click="showBinding">查看</el-button>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="名称：">
                                            <span>{{ mainInfo.secondParty.name }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="统一社会信用代码：">
                                            <span>{{mainInfo.secondParty.socialCode }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="法人代表：">
                                            <span>{{ mainInfo.secondParty.legalRepresentative }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="开户银行：">
                                            <span>{{ mainInfo.secondParty.bankName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="开户账号：">
                                            <span>{{ mainInfo.secondParty.accountNumber }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="联系电话：">
                                            <span>{{ mainInfo.secondParty.phone }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="邮政编码：">
                                            <span>{{  mainInfo.secondParty.postalCode }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="委托代理：">
                                            <span>{{ mainInfo.secondParty.principalAgent }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="传 真：">
                                            <span>{{ mainInfo.secondParty.fax }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="所在地址：">
                                            <span> {{  showAddress(mainInfo.secondParty.address) }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <div class="mainTitle">公证信息</div>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="公证机关：">
                                            <span>{{ mainInfo.notarization.name }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="公证日期：">
                                            <span>{{ mainInfo.notarization.notaryTime }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="开户银行：">
                                            <span>{{ mainInfo.notarization.bankName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="开户账号：">
                                            <span>{{ mainInfo.notarization.accountNumber }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="公证意见：" >
                                            <span>{{ mainInfo.notarization.opinion }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <!-- 合同清单 审核可以修改-->
                    <div id="contractListCon" class="con">
                        <div class="tabs-title" id="contractList">合同清单</div>
                        <TreeContractListChange ref="TreeContractList" v-model="contractListTable" :isBidding="isBidding" :billid="billid" :mainInfo="mainInfo" @isSearch="isContructSearch" :errorMsg='errorContractMsg' @isMonitorTaxRate="isMonitorTaxRate = true"  :auditState="auditState" :isAdd="auditState.canModify"
                        :isEdit="auditState.canModify" :subcontract="subcontract" :state="formData.state" :period="formData.period"></TreeContractListChange>
                    </div>

                    <!-- 保证金 -->
                    <div id="earnestMoneyCon" class="con">
                        <div class="tabs-title" id="earnestMoney">保证金</div>
                        <BondChange  ref="Bond" v-model="earnestMoneyTable" :contractType="formData.contractType" :contractTypelist= "subTypeForm"  :billid="billid" :mainInfo="mainInfo" :errorMsg='errorBondMsg'  :auditState="auditState" :isAdd="auditState.canModify" :isEdit="auditState.canModify" :getTableData="getBondList"></BondChange>
                    </div>

                    <!-- 合同条款 -->
                    <div id="contractTermsCon" class="con">
                        <div class="tabs-title" id="contractTerms">
                            合同条款
                        </div>
                        <div class="e-table">
                            <div class="mainTitle">通用合同条款</div>
                            <el-table
                                :data="commonCtTermsTable"
                                border
                                style="width: 100%; margin-bottom: 20px"
                                class="table"
                            >
                                <el-table-column
                                    type="index"
                                    label="序号"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="mechanism"
                                    label="所属单位"
                                    width="250"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="templateCode"
                                    label="通用合同条款编号"
                                    width="270"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="clauseTemplate"
                                    label="合同条款名称"
                                    width="250"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="detailedQuery"
                                    label="条款明细查阅"
                                    class-name="blue-column"
                                >
                                    <template>
                                        <span>查看</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                        <div class="e-table">
                            <div class="mainTitle">项目专用合同条款</div>
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button
                                            size="small"
                                            type="primary"
                                            plain
                                            >新增</el-button
                                        >
                                        <el-button
                                            size="small"
                                            type="danger"
                                            plain
                                            >删除</el-button
                                        >
                                    </div>
                                </div>
                            </div>
                            <el-table
                                :data="onlyCtTermsTable"
                                border
                                style="width: 100%; margin-bottom: 20px"
                                class="table"
                            >
                                <el-table-column
                                    type="index"
                                    label="序号"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="entryCode"
                                    label="条目号"
                                    width="250"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="clauseContent"
                                    label="原条款内容"
                                    width="270"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="specialConditions"
                                    label="专用合同条款内容"
                                    show-overflow-tooltip
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp
                            :relationId="attachId"
                            bucketName="subcontract"
                        />
                    </div>

                     <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <AuditHistoryIndex :billType="7021"></AuditHistoryIndex>
                    </div>

                    <!-- 变更签订记录-->
                    <div id="changeSignLogCon" class="con">
                        <div class="tabs-title" id="changeSignLog">变更签订记录</div>
                        <div class="e-table">
                            <el-table
                                :data="signLogTable" ref="signLogTable" v-sortTable="{ 'tableData': signLogTable, '_this': this, 'ref': 'signLogTable' }"
                                border
                                style="width: 100%"
                            >
                                <el-table-column prop="signingDate" label="变更签订日期" width="300">
                                </el-table-column>
                                <el-table-column prop="financialSharing" label="传输财务共享" min-width="300" class-name="blue-column">
                                    <template slot-scope="{ row }">
                                        <span  @click="changeSignLog(row)">{{ financialSharingList[row.financialSharing ? row.financialSharing:0] }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="founderName" label="经办人">
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <ComExaButtons :auditState="auditState" :state="formData.state" @exas="exas" :founderId="formData.founderId" />
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>

    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapState, mapMutations } from 'vuex'
import fn from '@/utils/checkEmpty.js'
import AttachComp from '@/components/common/attachIndex'
import count from '@/utils/contractCount.js'
import otherContractsApply from '@/api/balanceContractApi/otherContractsApi/otherContractsApply.js'
import otherContractsChangeApply from '@/api/balanceContractApi/otherContractsApi/otherContractsChangeApply.js'
import auditRequest from '@/api/subcontractApi/audit.js'
import { getRmbRate } from '@/api/equip/common.js'
import TreeContractListChange from '@/pages/otherContracts/publicList/treeContractListChange.vue'
import $ from 'jquery'
import { selectDataClient, showLoading, hideLoading } from '@/utils/common'
import AuditHistoryIndex from '@/pages/subcontract/components/auditHistory/auditHistoryIndex.vue'
import BondChange from '@/pages/otherContracts/publicList/bondChange.vue'
import { showContract } from '@/pages/subcontract/common/contractCom.js'
import { exas, showBinding, saveAll, submitCommit } from '@/pages/subcontract/common/contractCom.js'
export default {
    data () {
        return {
            //基本信息表单数据
            formData: {
                'address': '',
                'advanceCharge': 0,
                'advanceChargeProportion': 0,
                'baseCurId': '',
                'baseCurName': '',
                'baseCurRate': 0,
                'billId': '',
                'bondAmount': 0,
                'bondState': true,
                'changeState': 0,
                'contractAmount': 0,
                'contractContext': '',
                'contractName': '',
                'contractNumber': '',
                'contractState': 0,
                'contractType': 0,
                'contractTypeName': '',
                'currencyId': '',
                'currencyName': '',
                'deposit': 0,
                'financialSharing': 0,
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'period': 0,
                'rmbName': '',
                'rmbRate': 0,
                'signingDate': '',
                'signingEndTime': '',
                'signingId': '',
                'signingName': '',
                'signingStartTime': '',
                'state': 0,
                'taxAmount': 0,
                'taxExcludedAmount': 0,
                'taxRate': 0,
                'workId': ''
            },
            //主体信息表单数据
            mainInfo: {
                firstParty: {
                    accountNumber: '',
                    address: '',
                    bankName: '',
                    billId: '',
                    fax: '',
                    legalRepresentative: '',
                    orgId: '',
                    orgName: '',
                    phone: '',
                    postalCode: '',
                    principalAgent: '',
                    sourceId: ''
                },
                notarization: {
                    accountNumber: '',
                    bankName: '',
                    billId: '',
                    name: '',
                    notaryTime: '',
                    opinion: '',
                    sourceId: this.$route.query.billid
                },
                secondParty: {
                    'accountNumber': '',
                    'address': '',
                    'bankName': '',
                    'biddingId': '',
                    'biddingName': '',
                    'billId': '',
                    'dtlId': '',
                    'fax': '',
                    'id': '',
                    'legalRepresentative': '',
                    'name': '',
                    'phone': '',
                    'postalCode': '',
                    'principalAgent': '',
                    'socialCode': '',
                    sourceId: this.$route.query.billid
                }
            },
            formLabelWidth: '195px',
            ctsubcontractId: '', //合同id
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            errorList: [], //控制导航栏感叹号的显示
            contractListTable: [], //合同清单表格数据
            goodsListTable: [], //物资清单表格数据
            equipListTable: [], //设备清单表格数据
            deviceListTable: [], //设备清单表格数据
            earnestMoneyTable: [], //保证金表格数据
            commonCtTermsTable: [], //通用合同条款表格数据
            onlyCtTermsTable: [], //项目专用合同条款表格数据
            attachTable: [], //附件信息表格数据
            auditHistoryTable: [], //审核历史表格数据
            signLogTable: [], //签订记录表格数据
            changeLogTable: [], //变更历史表格数据
            settlementParameterTable: [], //结算台账表格数据
            terminationLogTable: [], //终止记录表格数据
            objFlag: {
                //判断是否转圈圈
                flag1: false,
                flag2: false,
                flag3: false,
                flag4: false,
                flag5: false,
                flag6: false,
                flag7: false,
                flag8: false,
                flag9: false,
                flag10: false,
                flag11: false,
                flag12: false
            },
            billid: this.$route.query.billid,
            rulesBase: {
                contractName: [
                    { required: true, message: '请输入合同名称', trigger: 'blur' },
                ],
                taxAmount: [
                    { required: true, message: '请输入税额', trigger: 'blur' },
                ],
                contractType: [
                    { required: true, message: '请选择合同类型', trigger: 'change' },
                ],
                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'change' },
                ],
                taxRate: [
                    { required: true, message: '请输入0-100的数字', trigger: 'blur' },
                ],
                deposit: [
                    { required: false, message: '请输入押金', trigger: 'blur' },
                ],
                nailDetailedListState: [
                    { required: true, message: '请选择是否需要甲供清单', trigger: 'change' },
                ],
                bondState: [
                    { required: true, message: '请选择是否需要缴纳履约保证金：', trigger: 'change' },
                ],
                bondAmount: [
                    {
                        required: false,
                        validator: (rule, value, callback)=>{
                            console.log('value', value)
                            if(this.formData.bondState) {
                                if(!this.formData.bondAmount || this.formData.bondAmount <= 0) {
                                    callback('应交履约保证金必须大于0')
                                }else{
                                    callback()
                                }
                            }else{
                                callback()
                            }

                        },
                        trigger: 'blur'
                    }
                ],
                contractContext: [
                    { required: true, message: '请输入主要合同内容', trigger: 'blur' },
                    { min: 1, max: 500, message: '最多输入500字', trigger: 'blur' }
                ],
            },
            rulesMain: {
                'firstParty.orgName': [
                    {
                        required: true,
                        message: '请选择本机构及其上级单位的数据',
                        trigger: 'blur'
                    }
                ],
                'secondParty.name': [
                    { required: true, message: '请选择数据', trigger: 'blur' }
                ],
                'secondParty.legalRepresentative': [
                    {
                        required: true,
                        message: '请输入法人代表',
                        trigger: 'blur'
                    },
                    { validator: this.textLen, trigger: 'blur' }
                ],
                'secondParty.phone': [
                    {
                        required: true,
                        message: '请输入电话号码',
                        trigger: 'blur'
                    },
                    { validator: this.phoneTest, trigger: 'blur' }
                ],
                'secondParty.bankName': [
                    {
                        required: true,
                        message: '请输入开户银行',
                        trigger: 'blur'
                    }
                ],
                'secondParty.accountNumber': [
                    {
                        required: true,
                        message: '请输入开户账号',
                        trigger: 'blur'
                    }
                ],
                'secondParty.socialCode': [
                    {
                        required: true,
                        message: '请输入统一社会信用代码',
                        trigger: 'blur'
                    }
                ],
                'secondParty.postalCode': [
                    {
                        required: false,
                        validator: this.postalCodeTest,
                        trigger: 'change'
                    }
                ]
            },
            disabled: false, //是否禁止
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 7021
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 7021,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: ''
            },
            isContructSearchKey: false,
            errorContractMsg: [],
            TreeContractListShow: true,
            MaterialListShow: true,
            isMonitorTaxRate: false, //是否计算税率
            subcontract: null, //当前页面的api
            subTypeForm: ['房屋租赁、征地拆迁', '非生产性开支'], //合同类型
            errorMaterialMsg: [],
            errorBondMsg: [],
            bondState: false, //原合同是否应交履约保证金
        }
    },
    components: {
        AttachComp,
        TreeContractListChange,
        AuditHistoryIndex,
        BondChange
    },
    created () {
        this.init()
        this.subcontract = otherContractsChangeApply

    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()
        // 保存所有tabName
        const arr = [
            'baseInfo',
            'mainInfo',
            'contractList',
            'earnestMoney',
            'contractTerms',
            'attach',
            'auditHistory',
            'changeSignLog',
        ]
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        if(this.$route.query.name) {
            setTimeout(()=>{
                this.onChangeTab({
                    name: this.$route.query.name
                })
                this.tabsName = this.$route.query.name
            }, 200)
        }
    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            financialSharingList: state => state.contract.ctClassify.financialSharingList, //传输财务共享
        }),
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.$route.query.billid
        },
        //清单引入方式 0：从招标引入 1：从目标预算引入 2：从非生产性开支引入
        isBidding () {
            if(this.formData.contractType === 1) {
                return 1
            }else{
                return 2
            }
        },
        showAddress () {
            return value=>{
                if(!value) return ''
                try {
                    let obj = JSON.parse(value)
                    const  address = obj.address ? obj.address.join('-') : ''
                    const  detail = obj.detail
                    let str = ''
                    if(address && detail) {
                        str = address + '-' + detail
                    }else if(!address  && detail) {
                        str = detail
                    }else if(address  && !detail) {
                        str = address
                    }
                    return str
                }
                catch(err) {
                    return value
                }
            }
        }
    },
    watch: {
        //监听合同类型切换
        'formData.contractType': {
            handler (newData, oldData) {
                if (this.flag1 || this.flag2 || this.flag3 || this.flag4) {
                    if (this.subTypeForm[oldData - 1] !== undefined) {
                        this.clientPop(
                            'info',
                            `是否将【${this.subTypeForm[oldData - 1]}】更改为【${this.subTypeForm[newData - 1]}】？更改后将清空乙方、合同清单信息，请确认！`,
                            this.clearInfo
                        )
                    }
                }
                this.disabled = this.subTypeForm[newData - 1] === '内部班组' ? true : false
            }
        },
        //监听是否应交保证金切换
        'formData.bondState': {
            handler (val) {

                this.rulesBase.bondAmount[0].required = val
                if(val === false) {
                    this.formData.bondAmount = 0
                }
                if(this.$refs.rulesBase) {
                    let dome =  this.$refs.rulesBase.fields.find(x=>x._props.prop === 'bondAmount')
                    if(dome) {
                        dome.onFieldBlur()
                    }
                }
            },
            immediate: true
        },
        contractListTable: {
            handler (newData) {
                if(this.isMonitorTaxRate) {
                    if(newData.length > 0) {
                        let num = 0
                        newData.forEach(item=>{
                            if(item.changeState !== -1 )num += parseFloat(item.amountEndChange)
                        })
                        this.formData.taxExcludedAmount = parseInt(num)
                    }else{
                        this.formData.taxExcludedAmount = 0
                    }
                    this.monitorTaxRate()
                }
            },
            deep: true
        },
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    methods: {
        ...mapMutations(['setAuditParams']),
        ...mapMutations(['setSelectedInfo']),
        //初始化数据
        init () {
            showLoading()
            Promise.all([
                this.getBasic(),
                this.getMain(),
                this.getAuditHistory(),
                this.getChangeLog(),
                this.getSettlementParameter(),
                this.getTerminationLog(),
                this.getCurrentUnitInfo()  //获取流程按钮显示状态
            ]).finally(() => {
                hideLoading()
            })
        },
        //获取流程按钮显示状态
        getCurrentUnitInfo () {
            auditRequest.getUnitInfoByBillId(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        handleCurrency (val) {
            this.formData.currencyName = this.currencyForm.find(x=>x.value === val).label
            if(this.formData.currencyName === '人民币') {
                this.formData.rmbRate = 1
            }else{
                getRmbRate({
                    currency: val,
                    orgId: this.userInfo.orgInfo.orgId
                }).then(res=>{
                    this.formData.rmbRate = res.rate
                })
            }
            if(this.formData.currencyId === this.formData.baseCurId) {
                this.formData.scRate = 1
                this.showBaseCurName = false
            }else{
                this.showBaseCurName = true
            }
        },
        //取消
        handleClose () {
            hideLoading()
            this.$router.replace('/otherContractList')
        },
        //判断主体信息或合同清单是否存在数据
        test () {
            //有数据为 true
            this.flag1 = !this.checkEmpty(this.mainInfo.firstParty)
            this.flag2 = !this.checkEmpty(this.mainInfo.notarization)
            this.flag3 = !this.checkEmpty(this.mainInfo.secondParty)
            this.flag4 = !this.checkEmpty(this.contractListTable)
        },
        //清空乙方和合同清单数据
        clearInfo () {
            this.$refs.TreeContractList.clearData()
            this.mainInfo.secondParty = {
                accountNumber: '',
                address: '',
                bankName: '',
                biddingName: '',
                biddingId: '',
                billId: '',
                fax: '',
                legalRepresentative: '',
                name: '',
                phone: '',
                postalCode: '',
                principalAgent: '',
                socialCode: '',
                dtlId: '',
                sourceId: this.$route.query.billid
            }
        },
        //点击招标弹窗
        handleBidding () {

            if(this.disabled) return
            if (this.mainInfo.secondParty.name || this.flag4) {
                this.clientPop(
                    'info',
                    '是否更改？更改后将清空乙方、合同清单信息，请确认！',
                    ()=>{
                        this.clearInfo()
                        this.biddingClient()
                    }
                )
            }else{
                this.biddingClient()
            }
        },
        //弹出招标弹窗
        biddingClient () {
            selectDataClient({
                SelectServiceToken: '/tender/apply/selectTenderApply', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify({
                    'contractType': [],
                    'key': '',
                    'limit': 10,
                    'page': 1,
                    'tenderApplyId': '',
                    'tenderClass': []
                }), //初始化参数
                Title: '选择招标' // 标题
            }).then(val => {
                this.mainInfo.secondParty.biddingName = val[0] ? val[0].tenderName : ''
                this.mainInfo.secondParty.biddingId = val[0] ?  val[0].billId : ''
            })

        },
        //点击乙方名称弹窗
        handleName () {
            if (!this.checkEmpty(this.contractListTable)) {
                this.clientPop(
                    'info',
                    '是否更改？更改后将清空合同清单信息，请确认！',
                    ()=>{
                        this.clearInfo()
                        if(this.mainInfo.secondParty.biddingId) {
                            const ids = this.mainInfo.secondParty.id ? [JSON.stringify({ 'dtlId': this.mainInfo.secondParty.dtlId, 'subcontractorId': this.mainInfo.secondParty.id })] : []
                            selectDataClient({
                                SelectServiceToken: '/tender/result/getCandidate', // 客户端对应方法名
                                IsSingleMode: true, // 是否单选 true 单选 false 多选
                                SelectedIDs: ids, // 已选中id
                                InitParamsStr: this.mainInfo.secondParty.biddingId, //初始化参数
                                Title: '选择乙方' // 标题
                            }).then(val => {
                                this.mainInfo.secondParty.id = val[0].subcontractorId
                                this.mainInfo.secondParty.dtlId = val[0].dtlId
                                this.mainInfo.secondParty.name = val[0].getSubcontractorName
                            })
                        }else{
                            let InitParamsStr = null
                            let ids = null
                            if (
                                this.subTypeForm[this.formData.contractType - 1] === '房屋租赁、征地拆迁'
                            ) {
                                InitParamsStr = JSON.stringify({ //选择本机构的单位类型是个人、政府的往来单位
                                    'type': null,
                                    'businessUnitType': ['0', '2'],
                                    'keyword': null,
                                    'outerType': [],
                                    'limit': 10,
                                    'page': 1
                                })
                                ids = []
                            } else {
                                InitParamsStr = JSON.stringify({ //选择合格分包商、合格供应商和本机构往来单位
                                    'type': [0, 1, 2],
                                    'businessUnitType': 0,
                                    'keyword': null,
                                    'outerType': [],
                                    'limit': 10,
                                    'page': 1
                                })
                                ids = []
                            }
                            selectDataClient({
                                SelectServiceToken: '/GeneralSelectOuter', // 客户端对应方法名
                                IsSingleMode: true, // 是否单选 true 单选 false 多选
                                SelectedIDs: ids, // 已选中id
                                InitParamsStr: InitParamsStr,
                                Title: '选择往来单位' // 标题
                            }).then(val => {
                                this.mainInfo.secondParty.id = val[0].id
                                this.mainInfo.secondParty.name = val[0].outerName
                                this.mainInfo.secondParty.socialCode = val[0].creditCode
                            })
                        }
                    }
                )
            }
            else{
                if(this.mainInfo.secondParty.biddingId) {
                    const ids = this.mainInfo.secondParty.id ? [JSON.stringify({ 'dtlId': this.mainInfo.secondParty.dtlId, 'subcontractorId': this.mainInfo.secondParty.id })] : []
                    selectDataClient({
                        SelectServiceToken: '/tender/result/getCandidate', // 客户端对应方法名
                        IsSingleMode: true, // 是否单选 true 单选 false 多选
                        SelectedIDs: ids, // 已选中id
                        InitParamsStr: this.mainInfo.secondParty.biddingId, //初始化参数
                        Title: '选择乙方' // 标题
                    }).then(val => {
                        this.mainInfo.secondParty.id = val[0].subcontractorId
                        this.mainInfo.secondParty.dtlId = val[0].dtlId
                        this.mainInfo.secondParty.name = val[0].getSubcontractorName
                    })
                }else{
                    let InitParamsStr = null
                    let ids = null
                    if (
                        this.subTypeForm[this.formData.contractType - 1] === '房屋租赁、征地拆迁'
                    ) {
                        InitParamsStr = JSON.stringify({
                            'type': null,
                            'businessUnitType': ['0', '2'],
                            'keyword': null,
                            'outerType': [],
                            'limit': 10,
                            'page': 1
                        })
                        ids = []
                    } else {
                        InitParamsStr = JSON.stringify({
                            'type': [0, 1, 2],
                            'businessUnitType': 0,
                            'keyword': null,
                            'outerType': [],
                            'limit': 10,
                            'page': 1
                        })
                        ids = []
                    }
                    selectDataClient({
                        SelectServiceToken: '/GeneralSelectOuter', // 客户端对应方法名
                        IsSingleMode: true, // 是否单选 true 单选 false 多选
                        SelectedIDs: ids, // 已选中id
                        InitParamsStr: InitParamsStr,
                        Title: '选择往来单位' // 标题
                    }).then(val => {
                        this.mainInfo.secondParty.id = val[0].id
                        this.mainInfo.secondParty.name = val[0].outerName
                        this.mainInfo.secondParty.socialCode = val[0].creditCode
                    })
                }
            }

        },

        //计算
        count () {
            //计算税额 税额=税率*不含税金额
            this.formData.taxAmount = count.countTax(
                +this.formData.taxRate,
                this.formData.taxExcludedAmount
            )
            //计算合同金额 合同金额=不含税金额+税额
            this.formData.amountAfterChange = count.countMoney(
                this.formData.taxExcludedAmount,
                +this.formData.taxAmount
            )
        },
        //监听税率
        monitorTaxRate () {
            this.count()
        },
        //监听税额
        monitorTax () {
            this.formData.amountAfterChange = count.countMoney(
                this.formData.taxExcludedAmount,
                +this.formData.taxAmount
            )
        },
        //监听预付款金额
        monitorMoney () {
            this.formData.amountAfterChange = count.countMoney(
                this.formData.taxExcludedAmount,
                +this.formData.taxAmount
            )
        },
        //验证邮政编码
        postalCodeTest (rule, value, callback) {
            if (value === undefined || value === '' || value === null) {
                callback()
            }
            if (value.length == 6) {
                callback()
            } else {
                callback(new Error('请输入6位数'))
            }
        },
        //验证电话号码
        phoneTest (rule, value, callback) {
            const require = this.rulesMain[rule.field][0].required
            const reg = /^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/
            if (reg.test(value)) {
                callback()
            }else if(!value && !require) {
                callback()
            }
            else {
                callback(new Error('请输入有效电话'))
            }
        },
        //验证法人代表
        textLen (rule, value, callback) {
            if (value.length < 20) {
                callback()
            } else {
                callback(new Error('不能超过20个字'))
            }
        },
        //判断数据是否为空
        checkEmpty (datas) {
            return fn.checkEmpty(datas)
        },
        //根据id查询基础信息
        getBasic () {
            this.isMonitorTaxRate = false
            otherContractsChangeApply.getInfo(this.billid).then(res => {
                this.formData = res
                const { baseCyByOrgId } = this.userInfo
                this.formData.baseCurName = baseCyByOrgId.currencyName  //本位币
                this.formData.baseCurId = baseCyByOrgId.currency
                otherContractsApply.getInfo(this.formData.originalBillId).then(res=>{
                    this.bondState = res.bondState
                })
                //this.count()
                this.getsignLog()
            })
        },
        //根据id查询主体信息
        getMain () {
            otherContractsChangeApply.getMainstay(this.billid).then(res => {
                const fn = feild=>{
                    if(res[feild]) {
                        for(let key in res[feild]) {
                            this.mainInfo[feild][key] = res[feild][key]
                        }
                    }
                }
                fn('firstParty')
                fn('notarization')
                fn('secondParty')
                if(!this.mainInfo.firstParty.orgId) {
                    this.mainInfo.firstParty.orgId = this.userInfo.orgInfo.orgId
                    this.mainInfo.firstParty.orgName = this.userInfo.orgInfo.orgName
                }
                this.mainInfo.firstParty.sourceId = this.mainInfo.firstParty.sourceId ? this.mainInfo.firstParty.sourceId : this.billid
                this.mainInfo.notarization.sourceId = this.mainInfo.notarization.sourceId ? this.mainInfo.notarization.sourceId : this.billid
                this.mainInfo.secondParty.sourceId = this.mainInfo.secondParty.sourceId ? this.mainInfo.secondParty.sourceId : this.billid
                this.test()
            })
        },
        //根据id查询合同清单
        getContractList () {
            this.$refs['TreeContractList'].getData()
        },
        //根据id查询甲供清单
        getArmorList () {
            this.$refs['MaterialList'].getData()
        },
        //保存甲供清单
        saveArmorList () {
            return new Promise((resolve, reject)=>{
                //保存物资清单
                if(this.goodsListTable.length === 0) {
                    this.clearError('armorList')
                    resolve()
                    return
                }
                let newListAll = []
                const treeChangeList = data=>{
                    data.forEach(item=>{
                        if(item.children.length > 0) {
                            treeChangeList(item.children)
                        }
                        item.children = []
                        newListAll.push(item)
                    })
                }
                treeChangeList([...this.goodsListTable])//将表格数据展平
                this.errorMaterialMsg = []
                newListAll.forEach(item=>{
                    if(item.mainMaterialFlag && item.hierarchyType === 3 && !item.unitPrice) {
                        this.setErrorMaterialMsg('请输入单价')
                    }
                    if(!item.mainMaterialFlag && item.hierarchyType === 2 && !item.amount) {
                        this.setErrorMaterialMsg('请输入金额')
                    }
                    if(!item.mainMaterialFlag && item.hierarchyType === 1 && item.supplyType === 1) {
                        if(!newListAll.find(x=>x.parentId === item.billId)) {
                            this.setErrorMaterialMsg('请添加物资类别')
                        }
                    }
                })
                if(this.errorMaterialMsg.length > 0) {
                    this.setError('armorList')
                    reject('甲供清单错误')
                    return
                }

                otherContractsChangeApply.createSupplyMaterialList(newListAll).then(() => {
                    this.clearError('armorList')
                    this.getArmorList()
                    resolve()
                }).catch(err=>{
                    this.setError('armorList')
                    reject(err)
                })
            })
        },
        //查询甲供清单设备清单
        getEquipmentList () {
            this.$refs['EquipList'].getData()
        },
        //新增甲供清单设备清单
        saveEquipmentList () {
            return new Promise((resolve, reject)=>{
                //保存设备清单
                if(this.equipListTable.length === 0) {
                    this.clearError('armorList')
                    resolve()
                    return
                }
                let newListAll = []
                const treeChangeList = data=>{
                    data.forEach(item=>{
                        if(item.children.length > 0) {
                            treeChangeList(item.children)
                        }
                        item.children = []
                        newListAll.push(item)
                    })
                }
                treeChangeList([...this.equipListTable])//将表格数据展平
                this.errorEquipMsg = []
                newListAll.forEach(item=>{
                    if(item.hierarchyType === 2 && !item.number) {
                        this.setErrorEquipMsg('请输入数量')
                    }
                    if(item.hierarchyType === 2 && !item.unitPrice) {
                        this.setErrorEquipMsg('请输入单价')
                    }
                    if(item.hierarchyType === 2 && !item.equipmentId) {
                        this.setErrorEquipMsg('请选择设备')
                    }
                    if(item.hierarchyType === 2 && !item.unitPrice) {
                        this.setErrorEquipMsg('请输入单价')
                    }
                })
                if(this.errorEquipMsg.length > 0) {
                    this.setError('armorList')
                    reject('设备清单错误')
                    return
                }
                otherContractsChangeApply.createEquipmentList(newListAll).then(() => {
                    this.clearError('armorList')
                    resolve()
                    this.getEquipmentList()
                }).catch(err=>{
                    this.setError('armorList')
                    reject(err)
                })
            })
        },
        //根据id查询保证金
        getEarnestMoney () {
            this.$refs['Bond'].getData()
        },
        //根据id查询合同条款
        getContractTerms () {
            this.objFlag.flag6 = true
        },
        //根据id查询附件信息
        getAttach () {
            this.objFlag.flag7 = true
        },
        //根据id查询审核历史
        getAuditHistory () {
            this.objFlag.flag8 = true
        },
        //根据id查询签订记录
        getsignLog () {
            otherContractsChangeApply.findBySigningRecord({
                originalBillId: this.billid,
                period: parseInt(this.formData.period),
            }).then(res=>{
                this.signLogTable = res.data === null ? [] : [res]
            })
        },
        //根据id查询变更历史
        getChangeLog () {
            otherContractsChangeApply.getChangeRecords({
                originalBillId: this.billid
            }).then(res=>{
                this.changeLogTable = res.data === null ? [] : res
            })
        },
        //根据id查询结算台账
        getSettlementParameter () {
            this.objFlag.flag11 = true
        },
        //根据id查询终止记录
        getTerminationLog () {
            otherContractsChangeApply.getStopRecord({
                sourceId: this.billid
            }).then(res=>{
                this.terminationLogTable = res.data === null ? [] : res
            })
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                this.$refs.rulesBase.validate(valid => {
                    if (valid) {
                        otherContractsChangeApply.createInfo(this.formData).then(() => {
                            this.clearError('baseInfo')
                            resolve()
                            this.getBasic()
                        }).catch(err=>{
                            reject(err)
                            this.setError('baseInfo')
                        })
                    } else {
                        this.setError('baseInfo')
                        reject('基本信息错误')
                    }
                })
            })

        },

        //新增(修改)主体信息
        createMainInfo () {
            return new Promise((resolve, reject)=>{
                this.$refs.rulesMain.validate(valid => {
                    if (valid) {

                        otherContractsChangeApply.createMainstay(this.mainInfo).then(() => {
                            this.str = JSON.stringify(this.mainInfo)
                            this.clearError('mainInfo')
                            resolve()
                            this.getMain()
                        }).catch(err=>{
                            this.setError('mainInfo')
                            reject(err)
                        })
                    } else {
                        this.setError('mainInfo')
                        reject('主体信息错误')
                    }
                })
            })
        },
        //删除基本信息
        deleteBaseInfo () {
            this.clientPop(
                'info',
                this.oneDeleteErr,
                ()=>{
                    showLoading()
                    otherContractsChangeApply.deleteInfo(this.billid).then(() => {
                        hideLoading()
                        this.clientPop('suc', '删除成功', this.handleClose)
                    })
                }
            )
        },

        //新增(修改)保证金
        createBond (isComit) {
            return new Promise((resolve, reject)=>{
                if(isComit) {
                    const arr = this.earnestMoneyTable.filter(x=>x.changeType !== -1)
                    this.errorBondMsg = []
                    arr.forEach(item=>{
                        if(item.deductionRatio === '' ||  item.deductionRatio === null) {
                            this.setErrorBondMsg('请输入扣款比例')
                        }
                    })
                    if(arr.length === 0) {
                        this.setErrorBondMsg('保证金不能为空，请选择。')
                        this.setError('earnestMoney')
                        reject('保证金错误')
                        return
                    }
                    if(this.errorBondMsg.length > 0) {
                        this.setError('earnestMoney')
                        reject('保证金错误')
                        return
                    }
                    otherContractsChangeApply.createBond(this.earnestMoneyTable).then(() => {
                        this.clearError('earnestMoney')
                        resolve()
                        this.getEarnestMoney()
                    }).catch(err=>{
                        this.setError('earnestMoney')
                        reject(err)
                    })
                }else{
                    if(this.earnestMoneyTable.length === 0) {
                        this.clearError('earnestMoney')
                        resolve()
                        return
                    }else{
                        otherContractsChangeApply.createBond(this.earnestMoneyTable).then(() => {
                            this.clearError('earnestMoney')
                            resolve()
                            this.getEarnestMoney()
                        }).catch(err=>{
                            this.setError('earnestMoney')
                            reject(err)
                        })
                    }
                }
            })

        },
        //是否是清单搜索
        isContructSearch (flag, data) {
            this.isContructSearchKey = flag
            this.isContructSearchData = data
        },
        //保存清单
        saveContractList (isComit = false) {
            return new Promise((resolve, reject)=>{
                let contractListTable = [...this.contractListTable]

                if(contractListTable.length === 0) {
                    if(isComit) {
                        this.setError('contractList')
                        reject('必须引入清单')
                        return
                    }else{
                        resolve()
                        return
                    }
                }
                this.errorContractMsg = []
                const mapTableData = {}
                const fn = data=>{
                    data.forEach(item=>{
                        mapTableData[item.billId] = item
                        if(this.isBidding === 2) {
                            if(item.parentId !== '0') {
                                if(item.isDetailed && item.changeState !== -1) {
                                    !item.quantityAfterChange && item.quantityAfterChange != 0 ? this.setErrorContractMsg('请填写数量')  : ''
                                }
                                if(item.isDetailed && item.changeState !== -1 && item.changeState === 1) {
                                    !item.unitPriceAfterChange && item.unitPriceAfterChange != 0  ? this.setErrorContractMsg('请填写单价')  : ''
                                }
                            }
                            if(item.children && item.children.length > 0) {
                                fn(item.children)
                            }
                        }else{
                            if(item.itemIsDetailed && item.identification === '项' && item.changeState !== -1) {
                                !item.itemNo ? this.setErrorContractMsg('请填写细目编号')  : ''
                                !item.itemName ?  this.setErrorContractMsg('请填写细目名称')  : ''
                                !item.unit ? this.setErrorContractMsg('请选择计量单位') : ''
                            }
                            if(item.structureId && mapTableData[item.parentId].unit === '总额' && item.changeState !== -1) {
                                !item.amountAfterChange ? this.setErrorContractMsg('请填写金额')  : ''
                            }
                            if(item.unit !== '总额' && item.itemIsDetailed && !item.structureId && item.changeState !== -1 && item.changeState === 1) {
                                !item.unitPriceAfterChange && item.unitPriceAfterChange != 0  ? this.setErrorContractMsg('请填写单价')  : ''
                            }
                            if(item.structureId && mapTableData[item.parentId].unit !== '总额' && item.changeState !== -1) {
                                !item.quantityAfterChange && item.quantityAfterChange != 0 ? this.setErrorContractMsg('请填写数量')  : ''
                            }
                            if(item.listIsDetailed && item.changeState !== -1) {
                                !item.unitPriceType ? this.setErrorContractMsg('请选择单价类型') : ''
                            }
                            if(item.children && item.children.length > 0) {
                                fn(item.children)
                            }
                        }

                    })
                }
                if (isComit) {
                    fn(contractListTable)
                }
                if(this.errorContractMsg.length > 0) {
                    this.setError('contractList')
                    reject('合同清单错误')
                    return
                }else{
                    this.clearError('contractList')
                }

                if(this.isContructSearchKey) {
                    contractListTable = this.isContructSearchData
                    let newListAll = []
                    const treeChangeList = data=>{
                        data.forEach(item=>{
                            if(item.children.length > 0) {
                                treeChangeList(item.children)
                            }
                            const obj = JSON.parse(JSON.stringify(item))
                            obj.children = []
                            newListAll.push(obj)
                        })
                    }
                    treeChangeList([...contractListTable])//将表格数据展平
                    newListAll =  newListAll.map(x=>{
                        const obj = {
                            'amount': 0,
                            'amountAfterChange': 0,
                            'amountEndChange': 0,
                            'amountLastChange': 0,
                            'amountUpdateFlag': false,
                            'billId': '',
                            'changeState': 0,
                            'changeType': 0,
                            'identification': '',
                            'isDetailed': false,
                            'itemIsDetailed': false,
                            'itemName': '',
                            'itemNo': '',
                            'listIsDetailed': false,
                            'oriBillId': '',
                            'oriIsDetailed': false,
                            'oriParentBillId': '',
                            'parentId': '',
                            'quantity': 0,
                            'quantityAfterChange': 0,
                            'quantityEndChange': 0,
                            'quantityLastChange': 0,
                            'quantityUpdateFlag': false,
                            'remarks': '',
                            'sourceId': '',
                            'structureId': '',
                            'structureName': '',
                            'structureNamePaths': '',
                            'structurePaths': '',
                            'unit': '',
                            'unitPrice': 0,
                            'unitPriceAfterChange': 0,
                            'unitPriceEndChange': 0,
                            'unitPriceLastChange': 0,
                            'unitPriceType': 0,
                            'unitPriceUpdateFlag': false,
                            'oriPrice': 0,
                        }
                        for(let key in obj) {
                            obj[key] = x[key]
                        }
                        if(obj.changeType === 1) {
                            obj['thisLevelId'] = obj['billId']
                            obj['parentBillId'] = obj['parentId']
                        }
                        return obj
                    })
                    if(newListAll.length === 0) {
                        resolve()
                        return false
                    }
                    console.log('newListAll', newListAll)
                    this.clientPop('err', '保存搜索的数据会覆盖原数据，是否继续？', () => {
                        otherContractsChangeApply.saveContractList(newListAll).then(()=>{
                            this.getContractList()
                            this.clearError('contractList')
                            resolve()
                        }).catch(err=>{
                            this.errorContractMsg[0] = err
                            this.setError('contractList')
                            reject(err)
                        })
                    })
                }else{
                    let newListAll = []
                    const treeChangeList = data=>{
                        data.forEach(item=>{
                            if(item.children.length > 0) {
                                treeChangeList(item.children)
                            }
                            const obj = JSON.parse(JSON.stringify(item))
                            obj.children = []
                            newListAll.push(obj)
                        })
                    }
                    treeChangeList( [...this.contractListTable] )//将表格数据展平
                    newListAll =  newListAll.map(x=>{
                        const obj = {
                            'amount': 0,
                            'amountAfterChange': 0,
                            'amountEndChange': 0,
                            'amountLastChange': 0,
                            'amountUpdateFlag': false,
                            'billId': '',
                            'changeState': 0,
                            'changeType': 0,
                            'identification': '',
                            'isDetailed': false,
                            'itemIsDetailed': false,
                            'itemName': '',
                            'itemNo': '',
                            'listIsDetailed': false,
                            'oriBillId': '',
                            'oriIsDetailed': false,
                            'oriParentBillId': '',
                            'parentId': '',
                            'quantity': 0,
                            'quantityAfterChange': 0,
                            'quantityEndChange': 0,
                            'quantityLastChange': 0,
                            'quantityUpdateFlag': false,
                            'remarks': '',
                            'sourceId': '',
                            'structureId': '',
                            'structureName': '',
                            'structureNamePaths': '',
                            'structurePaths': '',
                            'unit': '',
                            'unitPrice': 0,
                            'unitPriceAfterChange': 0,
                            'unitPriceEndChange': 0,
                            'unitPriceLastChange': 0,
                            'unitPriceType': 0,
                            'unitPriceUpdateFlag': false,
                            'oriPrice': 0,
                        }
                        for(let key in obj) {
                            obj[key] = x[key]
                        }
                        return obj
                    })
                    if(newListAll.length === 0) {
                        resolve()
                        return false
                    }
                    console.log('newListAll', newListAll)
                    otherContractsChangeApply.saveContractList(newListAll).then(()=>{
                        this.clearError('contractList')
                        resolve()
                        this.getContractList()
                    }).catch(err=>{
                        this.errorContractMsg[0] = err
                        this.setError('contractList')
                        reject(err)
                    })
                }
            })

        },
        setErrorContractMsg (msg) {
            let index = this.errorContractMsg.findIndex(x=>x === msg)
            if(index === -1) {
                this.errorContractMsg.push(msg)
            }
        },
        setErrorMaterialMsg (msg) {
            let index = this.errorMaterialMsg.findIndex(x=>x === msg)
            if(index === -1) {
                this.errorMaterialMsg.push(msg)
            }
        },
        setErrorEquipMsg (msg) {
            let index = this.errorEquipMsg.findIndex(x=>x === msg)
            if(index === -1) {
                this.errorEquipMsg.push(msg)
            }
        },
        setErrorBondMsg (msg) {
            let index = this.errorBondMsg.findIndex(x=>x === msg)
            if(index === -1) {
                this.errorBondMsg.push(msg)
            }
        },
        //保存全部数据
        saveAll () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.saveContractList(),
                    this.createBond(),
                ]
            }
            saveAll(this, requestFn)
        },
        //保存并提交
        submitCommit () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.saveContractList(true),
                    this.createBond(true),
                ]
            }
            submitCommit(this, requestFn)
        },
        //保存
        submit () {
            this.saveAll()
        },
        // 审核相关操作
        async exas (arg) {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.saveContractList(true),
                    this.createBond(true),
                ]
            }
            exas(arg, this, requestFn)
        },
        //删除所有信息
        deleteData () {
            this.deleteBaseInfo()
        },
        //去合同签订页面
        goSigningPage () {
            const billid = this.billid
            this.$router.push({
                path: '/otherContractChangeSigningAdd',
                query: {
                    billid,
                    originalBillId: this.formData.originalBillId
                }
            })
        },
        //去合同变更页面
        goCtChangePage () {
            const billid = this.billid
            this.$router.push({
                path: '/changeContractDefinitionAdd',
                query: { billid }
            })
        },
        //去合同终止页面
        goCtEndPage () {
            const billid = this.billid
            this.$router.push({
                path: '/endContractAdd',
                query: { billid }
            })
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('auditHistory')) {
                    const lastConHeight =
                        document.getElementById('auditHistory').offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //清除错误标签
        clearError (name) {
            const index = this.errorList.findIndex(x=>x === name)
            if(index !== -1) {
                this.errorList.splice(index, 1)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        //选择本机级上级机构
        selectOrg () {
            selectDataClient({
                SelectServiceToken: '/hr/org/getParentOrg', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                Title: '选择机构' // 标题
            }).then(val => {
                this.mainInfo.firstParty.orgName = val[0].orgName
                this.mainInfo.firstParty.orgId = val[0].orgId
            })
        },
        //获取合同清单数据
        getContractData (params) {
            return  otherContractsChangeApply.getContractList(params)
        },
        //获取保证金接口
        getBondList (params) {
            return  otherContractsChangeApply.getBond(params)
        },
        //跳转到变更签订
        changeSignLog (row) {
            // if(row.financialSharing === 0 || row.financialSharing === 4) {
            //     this.$router.push({
            //         path: '/contractSigningEdit',
            //         query: {
            //             billid: row.billId
            //         }
            //     })
            // }else{
            //     this.$router.push({
            //         path: '/contractSigningShow',
            //         query: {
            //             billid: row.billId
            //         }
            //     })
            // }
            if(row.state === -1 || row.state === 2 || row.state === 5 || !this.permission(['edit'])) {
                this.$router.push({
                    path: '/otherContractChangeSigningShow',
                    query: {
                        billid: row.billId,
                        originalBillId: this.formData.originalBillId
                    }
                })
            }else{
                const auditParams = {
                    'billId': row.billId,
                    'billType': 7022//变更签订billType
                }
                auditRequest.getUnitInfoByBillId(auditParams).then(res => {
                    if(res.canModify) {
                        this.$router.push({
                            path: '/otherContractChangeSigningEdit',
                            query: {
                                billid: row.billId,
                                originalBillId: this.formData.originalBillId
                            }
                        })
                    }else{
                        this.$router.push({
                            path: '/otherContractChangeSigningShow',
                            query: {
                                billid: row.billId,
                                originalBillId: this.formData.originalBillId
                            }
                        })
                    }
                })
            }
        },
        //跳转到合同申请变更
        changeLog (row) {
            if(row.period === 0) {
                this.$router.push({
                    path: '/otherContractChangeApplyShow',
                    query: { billid: row.billId, originalBillId: this.billid, period: row.period }
                })
                return
            }
            if(row.state === -1 || row.state === 2 || row.state === 5 || !this.permission(['edit'])) {
                this.$router.push({
                    path: '/otherContractChangeApplyShow',
                    query: { billid: row.billId, originalBillId: this.billid, period: row.period }
                })
            }else{
                const auditParams = {
                    'billId': row.billId,
                    'billType': 7021//合同申请变更billType
                }
                auditRequest.getUnitInfoByBillId(auditParams).then(res => {
                    if(res.canModify) {
                        this.$router.push({
                            path: '/otherContractChangeApplyEdit',
                            query: { billid: row.billId, originalBillId: this.billid, period: row.period  }
                        })
                    }else{
                        this.$router.push({
                            path: '/otherContractChangeApplyShow',
                            query: { billid: row.billId, originalBillId: this.billid, period: row.period  }
                        })
                    }
                })
            }
        },
        //跳转到合同终止
        changeTerminationLog (row) {
            if(row.state === -1 || row.state === 2 || row.state === 5 || !this.permission(['edit'])) {
                this.$router.push({
                    path: '/otherContractSigningShow',
                    query: { billid: row.billId, originalBillId: this.billid }
                })
            }else{
                const auditParams = {
                    'billId': row.billId,
                    'billType': 7023 //合同终止billType
                }
                auditRequest.getUnitInfoByBillId(auditParams).then(res => {
                    if(res.canModify) {
                        this.$router.push({
                            path: '/otherContractSigningEdit',
                            query: { billid: row.billId, originalBillId: this.billid }
                        })
                    }else{
                        this.$router.push({
                            path: '/otherContractSigningShow',
                            query: { billid: row.billId, originalBillId: this.billid }
                        })
                    }
                })
            }
        },
        //跳转到合同申请查看页面
        jumpContractDefinitionShow () {
            showContract('otherContractApplyShow', this.formData.originalBillId)
        },
        //查看招标
        showBinding () {
            showBinding('otherBiddingApplicationEdit', this.mainInfo.secondParty.biddingId)
        },
    }
}
</script>

<style lang="scss" scoped>
.mainTitle {
    box-sizing: border-box;
    width: 100%;
    height: 40px;
    line-height: 40px;
    background: rgb(246, 246, 246);
    border: 1px solid rgb(236, 236, 236);
    margin: auto;
    margin-bottom: 15px;
    padding-left: 10px;
}
.e-table {
    min-height: auto;
    background: #fff;
}
.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

::v-deep.el-input--suffix .el-input__inner {
    padding-right: 5px;
}

</style>
